#include "functions.h"

bool ball_upd(char map[][WIDTH], const int B1, const int B2, struct ball *b)
{
    extern int who_win;
    //为了判断与板子的碰撞使用int
    int y_next = (*b).pos[Y_POS] + (*b).dirc[Y_POS] * (*b).speed,
        x_next = (*b).pos[X_POS] + (*b).dirc[X_POS] * (*b).speed;
    float factor;
    // game over?
    if (x_next <= 0)
    {
        who_win = RIGHTWIN;
        return false;
    }
    if (x_next >= WIDTH - 1)
    {
        who_win = LEFTWIN;
        return false;
    }
    //may hit the left board
    else if (x_next == 3)
    {
        ball_board_check(y_next, B1, b);
    }
    // may hit the right board
    else if (x_next == WIDTH - 3)
    {
        ball_board_check(y_next, B2,b);
    }
    // may hit top or bottom
    else if (y_next <= 0)
    {
        (*b).dirc[Y_POS] = 1;
        // cut the num so move smoothly
        b->pos[X_POS] = (float) (int) b->pos[X_POS];
        b->pos[Y_POS] = 1;
    }
    else if (y_next >= HEIGHT - 1)
    {
        (*b).dirc[Y_POS] = -1;
        // cut the num so move smoothly
        b->pos[X_POS] = (float) (int) b->pos[X_POS];
        b->pos[Y_POS] = HEIGHT - 2;
    }
    // to slow down when diag
    if ((*b).dirc[Y_POS] != 0) factor = 0.7;
    else factor = 1.1;
    // update the map
    int ballx, bally;
    ballx = (int)((*b).pos[X_POS] += (*b).dirc[X_POS] * ((*b).speed) * factor);
    bally = (int)((*b).pos[Y_POS] += (*b).dirc[Y_POS] * ((*b).speed) * factor);
#if DEBUG
#endif
    map[bally][ballx] = '@';
    return true;
}

void ball_board_check(int y_next, int B, struct ball * b)
{
    bool hit = false;
    if (y_next == B)
    {
        if (b->speed < 1.1)
        {
        (*b).speed *= 1.08;
        }
        (*b).dirc[X_POS] *= -1;
        (*b).dirc[Y_POS] = 0;
        printf("\a");
        hit = true;
    }
    else if (y_next == B + 1)
    {
        (*b).dirc[X_POS] *= -1;
        (*b).dirc[Y_POS] = 1;
        printf("\a");
        // slow down factor
        hit = true;
    }
    else if (y_next == B - 1)
    {
        (*b).dirc[X_POS] *= -1;
        (*b).dirc[Y_POS] = -1;
        printf("\a");
        // slowdown factor
        hit = true;
    }
    if (hit)
    {
        // cut the num so move smoothly
        b->pos[X_POS] = (float) (int) b->pos[X_POS];
        b->pos[Y_POS] = (float) (int) b->pos[Y_POS];
        hit = false;
    }
}

